package com.yst.webplugin.component;

import com.yst.webplugin.fieldhandler.FieldHandler;
import com.yst.webplugin.pathhandler.IPathHandler;
import com.yst.webplugin.pathhandler.PathHandlerUtils;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExecutionChain;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.HandlerMapping;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

@Component
public class FieldHandlerMapping implements HandlerMapping, Ordered {

    private final List<HandlerInterceptor> interceptors=new ArrayList<>();

    public FieldHandlerMapping(HandlerInterceptor...interceptors){
        this.interceptors.addAll(Arrays.asList(interceptors));
    }

    @Override
    public boolean usesPathPatterns() {
        return true;
    }

    @Override
    public HandlerExecutionChain getHandler(HttpServletRequest request) {
        Field field=ControllerUtil.getFieldByUrl(request.getRequestURI());
        if (Objects.nonNull(field)){
            return new HandlerExecutionChain(new FieldHandler(field),interceptors);
        }

        IPathHandler pathHandler=PathHandlerUtils.getHandler(request.getRequestURI());
        if (Objects.nonNull(pathHandler)){
            return new HandlerExecutionChain(pathHandler,interceptors);
        }
        return null;
    }

    private int order=20;
    public void setOrder(int order){
        this.order=order;
    }
    @Override
    public int getOrder() {
        return order;
    }
}
